generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  
  apiKey   ApiKey[]
  apiKeyId String?
  image    String?
  accounts Account[]
  sessions Session[]
  spaces SpaceUser[]
}

model ApiKey {
  id      String  @id @default(cuid())
  key     String  @unique
  enabled Boolean @default(true)
  User    User    @relation(fields: [userId], references: [id])
  userId  String

  requests ApiRequest[]

  @@unique([userId, key, enabled])
}

model ApiRequest {
  id        String   @id @default(cuid())
  timestamp DateTime @default(now())
  method    String
  path      String
  status    Int
  duration  Int

  usedApiKey String

  ApiKey   ApiKey @relation(fields: [apiKeyId], references: [id])
  apiKeyId String

  @@index([apiKeyId, timestamp])
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

model Space {
  id                String  @id @default(cuid())
  createdAt         DateTime @default(now())
  name String

  users  SpaceUser[]
  dashboards Dashboard[]
}

model SpaceUser {
  accessLevel Int @default(1)

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId String
  
  space Space @relation(fields: [spaceId], references: [id], onDelete: Cascade)
  spaceId String

  @@unique([userId, spaceId])
  @@index([spaceId])
}

model Dashboard {
  id                String  @id @default(cuid())
  name String
  createdAt         DateTime @default(now())

  space Space @relation(fields: [spaceId], references: [id], onDelete: Cascade)
  spaceId String
}